<template>
  <div class="applyPublish">
    <el-card>
      <div slot="header" class="clearfix">
        <span class="title">供应</span>
        <el-button class="bt" type="text" @click="exit">退出</el-button>
        <el-button class="bt" type="text" @click="deleteProduct">删除</el-button>
        <el-button class="bt" type="text" @click="save">保存</el-button>
      </div>
      <el-form
        ref="forms"
        :model="form"
        label-width="120px"
        label-position="left"
        :rules="rules"
      >
        <el-form-item label="货品标题" prop="product_name">
          <el-input
            v-model="form.product_name"
            placeholder="请输入货品标题"
            maxlength="10"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item label="货品分类" prop="type">
          <el-select v-model="form.type" placeholder="请选择货品分类">
            <el-option :label="item" :value="id" v-for="item,id in productCategory" :key="id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="轮播图" class="product-images">
          <div class="add">
            <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :http-request="httpRequestFn"
                :disabled="imgList.length > 3"
                :limit="1">
              <i class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="tips">
              <div class="text">图片数量1~4张，支持的图片格式：.jpg</div>
            </div>
          </div>
          <div class="images" v-if="imgList.length > 0">
            <div class="img" v-for="obj,id in imgList" :key="id">
              <img v-lazy="obj.photo_url">
              <div class="shade">
                <i class="el-icon-delete" @click="deleteImage(id)"></i>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="货品描述" prop="introduction">
          <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            show-word-limit
            maxlength="100"
            v-model="form.introduction"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="货品规格">
          <el-button type="primary" @click="addSize()">添加规格</el-button>

          <el-tag
            style="margin-left: 20px"
            closable
            v-for="(spe, id) in specificationList"
            :key="id"
            @close="deleteShowingSpecification(id)"
          >
            {{ spe.price }}<span style="color: red">￥</span>/{{ spe.name }}
            &nbsp;&nbsp;&nbsp;&nbsp;
            <span>{{ spe.mini_wholesale_quantity }}{{ spe.name }}</span
            >起批
          </el-tag>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            type="textarea"
            v-model="form.description"
            show-word-limit
            maxlength="200"
          ></el-input>
        </el-form-item>
        <el-form-item label="">
          <div class="tips">修改完记得保存哦~~</div>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 货品规格对话框 -->
    <el-dialog
      title="设置规格与价格"
      :visible.sync="dialogFormVisible"
      :show-close="showClo"
    >
      <el-form :model="specification" label-width="80px">
        <el-form-item label="计量单位">
          <el-input
            style="width: 100px"
            v-model="specification.name"
          ></el-input>
          <span style="color: #c0c4cc">&nbsp; 如 ： 斤、箱</span>
        </el-form-item>
        <el-form-item label="单价">
          <el-input
            style="width: 100px"
            v-model="specification.price"
          ></el-input>
          <span style="color: red">&nbsp; ￥</span>
        </el-form-item>
        <el-form-item label="起批量">
          <el-input
            style="width: 100px"
            v-model="specification.mini_wholesale_quantity"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="quitEditSpecification(true)"
          >保存</el-button
        >
        <el-button type="primary" @click="quitEditSpecification(false)"
          >取消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { upLoadPicture } from '@/utils/utils'
export default {
  name: "ApplyPublish",
  data() {
    var validateProduct_name = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入店铺名"));
      } else {
        callback();
      }
    };
    var validateIntroduction = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入商品描述"));
      } else {
        callback();
      }
    };
    var validate = (rule, value, callback) => {
      // console.log(rule);
      if (value === "") {
        callback(new Error("请选择分类"));
      } else {
        callback();
      }
    };
    var validateS = (rule, value, callback) => {
      if (this.form.specificationList.length === 0) {
        callback(new Error("请添加规格"));
      } else {
        callback();
      }
    };
    return {
      productCategory: this.$global.PRODUCTTYPE,
      dialogFormVisible: false, //货品规格对话框
      showClo: false,
      rules: {
        product_name: [{ validator: validateProduct_name, trigger: "blur" }],
        introduction: [{ validator: validateIntroduction, trigger: "blur" }],
        type: [{ validator: validate, trigger: "change" }],
        specificationList: [{ validator: validateS, trigger: "change" }],
      },
      form: {
        supplier_id: "",
        product_name: "",
        type: "",
        introduction: "",
        description: "",
        
      },
      specificationList: [],
      originSpecificationList: [],
      imgList: [],
      originImgList: [],
      specification: {
        //正在显示的规格
        product_id: undefined, //规格对应的商品id
        name: undefined, //规格单位 => unit
        price: undefined, //单价
        mini_wholesale_quantity: undefined, //最小供应量
      },
    };
  },
  methods: {
    deleteProduct() { //删除不彻底
      this.$confirm('是否确认删除这个供应?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$API.deleteSupply(this.$store.state.params.pid)
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.$router.go(-1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });         
      })
    },
    exit(){
      this.$router.go(-1)
    },
    // 删除图片
    deleteImage(id) {
      this.imgList.splice(id, 1)
    },
    // 删除正在展示的规格
    deleteShowingSpecification(id) {
      console.log(id);
      this.specificationList.splice(id, 1);
    },
    // 退出编辑规格
    quitEditSpecification(sign) {
      if (sign) this.specificationList.push(this.specification);
      (this.specification = {
        name: undefined,
        price: undefined,
        mini_wholesale_quantity: undefined,
      }),
        (this.dialogFormVisible = false);
    },
    httpRequestFn(res) {
      upLoadPicture(res, url => {
        this.imgList.push({
          "product_id": this.$store.state.params.pid,
          "photo_url": url
        })
       })
    },
    addSize() {
      this.dialogFormVisible = true;
    },
    // 发布供应
    save() {
      this.$refs.forms.validate((valid) => {
        if (!valid) {
          return this.$message({
            message: "请填写完整信息",
            type: "warning",
          });
        }
      });
      let sid = this.$store.state.saler.saler_id;
      if (!sid) {
        this.$message.warning("没登录");
        return;
      }
      this.form.supplier_id = sid;
      let pid = this.$store.state.params.pid
      let taskList = []
      taskList.push(this.$API.modifySupply(this.form, pid)) //基本信息上传
      for (let obj of this.originImgList) { // 图片地址删除
        taskList.push(this.$API.deleteProductPhotos(obj.id))
      }
      for (let obj of this.originSpecificationList) { // 规格删除
        taskList.push(this.$API.deleteSpecification(obj.id));
      }
      let taskList2 = []
      for (let obj of this.specificationList) { // 规格上传
        obj.product_id = pid;
        taskList2.push(this.$API.addSpecification(obj));
      }
      for (let obj of this.imgList) { // 图片地址上传
        taskList2.push(this.$API.addProductPhotos(obj))
      }
      Promise.all(taskList) .then((response) => {
        if ((response.status = 200)) {
          return Promise.all(taskList2)
        }
      }).then(res => {
        if ((res.status = 200)) {
          this.$message({
            message: "保存成功",
            type: "success",
          });
          this.load()
        }
      })
    },
    async load() {
      let pid = this.$store.state.params.pid
      await this.$API.getOneSupply(pid).then(res => {
        if (res.status == 200) {
          this.form = res.data
          return this.$API.getSpecification()
        }
      }).then(res => {
        if (res.status == 200) {
          this.specificationList = []
          for (let obj of res.data) {
            if (obj.product_id == this.$store.state.params.pid) {
              this.specificationList.push(obj)
            }
          }
          this.originSpecificationList = [...this.specificationList]
          return this.$API.getProductPhotos()
        }
      }).then(res => {
        if (res.status == 200) {
          this.imgList = []
          for (let obj of res.data) {
            if (obj.product_id == pid) {
              this.imgList.push(obj)
            }
          }
          this.originImgList = [...this.imgList]
        }
      })
    }
  },
  created() {
    this.load()
  },
};
</script>
<style lang="less" scoped>
.title{
  color: @color-theme;
}
i{
  &:hover{
    cursor: pointer;
  }
  user-select: none;
}
.tips{
  color: @color-tips;
}
.bt{
  float: right;
  margin-left: 15px;
}
.product-images{
  .add{
    display: flex;
    .tips{
      display: flex;
      flex-direction: column-reverse;
      padding-left: 20px;
    }
    .avatar-uploader {
      width: 100px;
      height: 100px;
      /deep/ .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
      }
      .el-upload:hover {
        border-color: #409eff;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #3264a9;
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
      }
    }
    margin-bottom: 20px;
  }
  .images{
    height: 100px;
    display: flex;
    
    .img{
      position: relative;
      margin-right: 20px;
      img{
        height: 100px;
      }
      &:hover .shade{
        display: flex;
      }
      .shade{
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        background: rgba(0,0,0,0.5);
        z-index: 2;
        i{
          font-size: 30px;
          color: #E6A23c;
        }
        display: none;
      }
    }
  }
}
</style>